<template>
  <md-page :title="pageTitle" isBtn :btnTextItems="data.btnTextItems" @btnClick="bottomBtnClick">
    <view class="container">
      <uni-forms ref="form" :modelValue="data.formData" :rules="data.rules" label-position="top" label-width="100">
        <!-- 举报原因单选列表 -->
        <uni-forms-item label="请选择举报原因" name="reason" required>
          <view class="radio-section">
            <uni-data-checkbox
              v-model="data.formData.reason"
              :localdata="data.reasonList"
              :multiple="false"
              mode="list" />
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
  </md-page>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { Toast } from '@/utils/util';
import type { BtnTextItem } from '@/components/md-ui/components/md-page/md-page.vue';
import { report, reasontype } from '@/api';
import { ReportSourceType } from '@/api/enum';

const reportType = ref<string>('bad_words'); // 默认不良言论举报

const pageTitle = computed(() => {
  return reportType.value === 'invalid_name' ? '违规队名举报' : '不良言论举报';
});

const data = reactive<any>({
  btnTextItems: [],
  formData: {
    reason: '',
    source_id: null,
  },
  reasonList: [],
  rules: {
    reason: {
      rules: [
        {
          required: true,
          errorMessage: '请选择举报原因',
        },
      ],
    },
  },
});

const form = ref<any>(null);

/**
 * 底部按钮点击事件
 */
const bottomBtnClick = async (info: { item: BtnTextItem }) => {
  const { key } = info.item;

  if (key === 'submit') {
    try {
      // 表单验证
      await form.value?.validate();

      // 额外验证：确保选择了举报原因
      if (!data.formData.reason) {
        Toast('请选择举报原因');
        return;
      }

      // 确认提交
      uni.showModal({
        title: '确认提交',
        content: '确认提交举报信息吗？提交后将无法修改。',
        success: async modalRes => {
          if (modalRes.confirm) {
            await submitReport();
          }
        },
      });
    } catch (error: any) {
      // 表单验证失败
      if (error?.length) {
        Toast(error[error.length - 1]?.errorMessage || '请完善表单信息');
      }
    }
  }
};

/**
 * 提交举报
 */
const submitReport = async () => {
  try {
    uni.showLoading({
      title: '提交中...',
      mask: true,
    });

    // 调用举报API
    const res = await report({
      ...data.formData,
      source_type: reportType.value === 'invalid_name' ? ReportSourceType.队名 : ReportSourceType.评论,
    });

    uni.hideLoading();

    // 显示成功提示
    uni.showModal({
      title: '提示',
      content: res?.msg || '已收到您的反馈，感谢您对社区美好氛围的贡献',
      showCancel: false,
      success: () => {
        // 返回上一页
        uni.navigateBack();
      },
    });
  } catch (error) {
    uni.hideLoading();
    Toast('提交失败，请重试');
    console.error('提交举报失败:', error);
  }
};

/**
 * 接口相关
 */
// 举报类型
const fetchReasontype = async () => {
  try {
    const res = await reasontype();
    data.reasonList = res.data?.map(item => ({ text: item, value: item }));
  } catch (error) {}
};

onLoad(option => {
  fetchReasontype();
  // 来源id，队伍id、文章id、评论id
  data.formData.source_id = option?.source_id;

  // 从页面参数获取举报类型
  if (option?.type) {
    reportType.value = option.type;
  }

  // 设置底部按钮
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  const commonStyle = (type: number) => ({
    color: configInfo?.['button_color' + type] || '#d92121',
    textColor: configInfo?.['button_color' + type + '_text'] || '#ffffff',
  });

  data.btnTextItems = [
    {
      text: '提交举报',
      key: 'submit',
      ...commonStyle(1),
    },
  ];
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  min-height: calc(100vh - 200rpx);

  .radio-section {
    margin-top: 20rpx;
  }

  :deep(.uni-forms-item) {
    margin-bottom: 40rpx;

    .uni-forms-item__label {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 20rpx;
    }
  }

  :deep(.uni-data-checklist) {
    .checklist-group {
      .checklist-box {
        padding: 30rpx 20rpx;
        margin-bottom: 20rpx;
        background: #ffffff;
        border-radius: 10rpx;
        border: 2rpx solid #e5e5e5;
        transition: all 0.3s;

        &.is-checked {
          border-color: #d92121;
          background: #fff5f5;
        }

        &:active {
          transform: scale(0.98);
        }

        .checklist-content {
          .checklist-text {
            font-size: 28rpx;
            color: #333;
          }
        }
      }
    }
  }
}
</style>
